"""
Created on 2020/12/29

@author: zengjw5
"""
import paramiko
import logging
import os
import sys
import getpass

class SCPClient(object):
    def __init__(self, user, password, port, ips, bucket=None):
        self.user = user
        self.password = password
        self.port = port
        self.ip = ips
        self.bucket = bucket

    def get_bucket(self):
        return self.bucket

    def connect(self):
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(self.ip, self.port, self.user, self.password)
            # print("scp连接已建立")
        except Exception as e:
            logging.error("scp未能连接到主机")
            # print("scp未能连接到主机")
    def cmd(self, cmd):
        # cmd = input("请输入要执行的命令:>>")
        stdout, stdin, stderr = self.ssh.exec_command(cmd)
        #print(sys.stdout.read())
    def upload(self, remote_file_abs, local_file_abs):
        try:
            self.connect()
            remote_file_dir = os.path.dirname(remote_file_abs)
            cmdStr = "if [ ! -d \""+remote_file_dir+"\" ];then mkdir "+remote_file_dir+"; fi"
            self.cmd(cmdStr)
            sftp = paramiko.SFTPClient.from_transport(self.ssh.get_transport())
            sftp = self.ssh.open_sftp()
            sftp.put(local_file_abs, remote_file_abs)
            self.close()
        except Exception as e:
            logging.error("上传失败："+str(e))
    def download(self, remote_file_abs, local_file_abs):
        try:
            self.connect()
            sftp = paramiko.SFTPClient.from_transport(self.ssh.get_transport())
            sftp = self.ssh.open_sftp()
            sftp.get(remote_file_abs, local_file_abs)
            self.close()
        except Exception as e:
            logging.error("下载失败："+str(e))
    def close(self):
        self.ssh.close()
        # print("scp连接关闭")



if __name__ == "__main__":
    scp_client = SCPClient("root", "7h2D8pwG", 22, "10.17.157.86", "/opt/AiStudio/ai-platform-training-master/data")
    scp_client.upload("/opt/zjw/test/test.csv", "D:/workspace/download/test3.csv")
    # scp_client.download("/opt/image_dectection/provider/file/upload/data_predict/zengjw5/525e5e563b834c5aa8c2c409dbed24c7.csv", "D:/workspace/download/test3.csv")
